package com.greet.service.impl;

import com.greet.context.BaseContext;
import com.greet.entity.AddressBook;
import com.greet.mapper.AddressBookMapper;
import com.greet.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> getByUserId(Long userId) {
        List<AddressBook> addressBooks = addressBookMapper.select(
                AddressBook.builder().userId(userId).build()
        );
        return addressBooks;
    }

    @Override
    public AddressBook getById(Long id) {
        List<AddressBook> addressBooks = addressBookMapper.select(
                AddressBook.builder().id(id).build()
        );
        return addressBooks.get(0);
    }

    @Override
    public AddressBook getByIsDefault(Long currentId, Integer isDefault) {
        List<AddressBook> addressBooks = addressBookMapper.select(
                AddressBook.builder().userId(currentId).isDefault(isDefault).build()
        );
        return addressBooks.get(0);
    }

    @Override
    public void setById(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void setDefault(Long UserId, Long id) {
        List<AddressBook> addressBooks = addressBookMapper.select(
                AddressBook.builder().userId(UserId).isDefault(1).build()
        );
        if (addressBooks != null && !addressBooks.isEmpty()){
            addressBookMapper.update(
                    AddressBook.builder().id(addressBooks.get(0).getId())
                            .isDefault(0).build()
            );
        }
        addressBookMapper.update(
                AddressBook.builder().id(id).isDefault(1).build()
        );

    }

    @Override
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
    }

    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }
}
